package com.xiaoxing.job;

import com.xiaoxing.domain.entity.Article;
import com.xiaoxing.mapper.ArticleMapper;
import com.xiaoxing.service.ArticleService;
import com.xiaoxing.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 实现定时任务的类
 * @author 李芋钢
 * @since 2023-01-18
 */

@Component
public class UpdateViewCountJob {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ArticleMapper articleMapper;

    @Scheduled(cron = "0/20 * * * * ?")
    public void updateViewCount(){
        //获取redis中的浏览量
        Map<String, Integer> viewCountMap = redisCache.getCacheMap("article:viewCount");
        List<Article> articles = articleService.list(null);
        for (Article article : articles) {
            Integer newViewCount = viewCountMap.get(article.getId().toString());
            if (newViewCount != null) {
                article.setViewCount(Long.valueOf(newViewCount));
            }
        }
        //更新到数据库中
        boolean b = articleService.updateBatchById(articles);
    }
}
